package com.swpu.project.Interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.swpu.project.constant.RedisConstant;
import com.swpu.project.model.dto.user.UserDto;
import com.swpu.project.util.UserHandler;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
/*
*  校验用户是否登录
*  刷新已登录用户的token时间
*
* */
public class RefreshInterceptor implements HandlerInterceptor {
    StringRedisTemplate stringRedisTemplate;
    public RefreshInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate=stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("helloworld");
        String token = request.getHeader("authorization").toString();
         if(StrUtil.isBlank(token))
             return true;
        String key= RedisConstant.USER_TOKEN_PREFIX+token;
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(key);
         if(entries==null||entries.isEmpty())

             return true;


        UserDto user= BeanUtil.fillBeanWithMap(entries,new UserDto(),true);
        UserHandler.saveUser(user);

        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

       UserHandler.removeUser();

    }



}
